package xidw_service

import (
	"context"
	"server/apps/xidw/xidw_mod"

	"go.uber.org/zap"

	"server/global"
	"server/utils"
)

type JwtService struct{}


func (jwtService *JwtService) JsonInBlacklist(jwtList xidw_mod.JwtBlacklist) (err error) {
	err = global.SysDB.Create(&jwtList).Error
	if err != nil {
		return
	}
	global.XidwCache.SetDefault(jwtList.Jwt, struct{}{})
	return
}


func (jwtService *JwtService) IsBlacklist(jwt string) bool {
	_, ok := global.XidwCache.Get(jwt)
	return ok
}


func (jwtService *JwtService) GetRedisJWT(userName string) (redisJWT string, err error) {
	redisJWT, err = global.XidwRedis.Get(context.Background(), userName).Result()
	return redisJWT, err
}


func (jwtService *JwtService) SetRedisJWT(jwt string, userName string) (err error) {
	dr, err := utils.ParseDuration(global.XidwConfig.JWT.ExpiresTime)
	if err != nil {
		return err
	}
	timer := dr
	err = global.XidwRedis.Set(context.Background(), userName, jwt, timer).Err()
	return err
}

func InitJwtBlackList() {
	var data []string
	err := global.SysDB.Model(&xidw_mod.JwtBlacklist{}).Select("jwt").Find(&data).Error
	if err != nil {
		global.Logger.Error("加载数据库jwt黑名单失败!", zap.Error(err))
		return
	}
	for i := 0; i < len(data); i++ {
		global.XidwCache.SetDefault(data[i], struct{}{})
	}
}
